let _config, _configMap, _dialogEnables, _instance;

// 加载默认按钮配置
export const loadButtonDialog = (btnGroup, instance) => {
  const { config = [], configMap = new Map(), dialogEnables = new Set() } = loadButtonConfig(btnGroup);
  _config = config;
  _configMap = configMap;
  _dialogEnables = dialogEnables;
  _instance = instance;
};


// 加载按钮配置
function loadButtonConfig(btnGroup) {
  const btnConfig = {};
  if(btnGroup && typeof btnGroup === "string") {
    try {
      const config = JSON.parse(btnGroup);
      btnConfig.config = config;
    } catch (error) { }
  }

  if(Array.isArray(btnConfig.config)) {
    const config = btnConfig.config;
    const configMap = new Map();
    const dialogEnables = new Set();
    config.forEach(btn => {
      const code = btn.nodeButtonCode;
      if(code) {
        configMap.set(code, btn);
      }
      const dialog = btn.dialog;
      if(dialog && dialog.enable) {
        dialogEnables.add(code);
      }
    })
    btnConfig.configMap = configMap;
    btnConfig.dialogEnables = dialogEnables;
  }
  return btnConfig;
}

// 是否开启了按钮的弹窗
function isDialogEnable(code) {
  return _dialogEnables.has(code);
}

// 按钮事件拦截
export const buttonEventInterceptor = (code, name, params) => {
  return new Promise((resolve, reject) => {
    if(isDialogEnable(code)) {
      const btnConfig = _configMap.get(code);
      openModal(btnConfig, params);
      resolve(true);
    }else{
      resolve(false);
    }
  })
}

// 打开弹窗
function openModal(option, params) {
  const _dialogInstance = _instance.$refs.buttonDialogRef;
  if(_dialogInstance && _dialogInstance.openModal) {
    _dialogInstance.openModal(option, params);
  }
}